/**
 * 
 */
package com.toncen.samepms.interceptor;

import java.sql.SQLException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.toncen.samepms.common.ActionException;
import com.toncen.samepms.common.ComitConstant;
import com.toncen.samepms.common.IJSONActionable;
import com.toncen.samepms.util.ErrorUtils;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
import com.sky.common.http.HTTPUtils;
import com.sky.common.string.StringUtils;

/**
 * 增加ActionError拦截器：在action方法执行过程中抛出异常后自动增加ActionError
 * 
 * @author tch
 * 
 */
public class ActionErrorInterceptor extends MethodFilterInterceptor {
	protected Log logger = LogFactory.getLog(this.getClass());

	/**
	 * 
	 */
	private static final long serialVersionUID = -7067045516670066374L;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.opensymphony.xwork2.interceptor.MethodFilterInterceptor#doIntercept(com.opensymphony.xwork2.ActionInvocation)
	 */
	@Override
	protected String doIntercept(ActionInvocation invocation) throws Exception {
		Object action = invocation.getAction();
		String result = "";
		try {
			result = invocation.invoke();
		} catch (Throwable e) {
			String message = e.getMessage();
			if (isSQLException(e) && !ComitConstant.isDeveloperMode()) {
				message = "";
			}
			if (StringUtils.isEmpty(message)) {
				message = "程序执行错误，请与系统管理员联系！\n错误类型：【" + e.getClass().getName() + "】";
			}
			if (ComitConstant.isDeveloperMode()) {
				e.printStackTrace();
			}
			((ActionSupport) action).addActionError(HTTPUtils.getSecurityString(message));
			ServletActionContext.getRequest().getSession().setAttribute(ActionErrorInterceptor.class.getName(), message);// 注入的错误信息
			logger.error(e.getMessage(), e);
			if (action instanceof IJSONActionable) {// JSON action
				IJSONActionable actionable = (IJSONActionable) action;
				actionable.setResult(false);
				actionable.setDescription(message);
				actionable.setContent(null);
			}
			if (e instanceof RuntimeException) {// 运行时异常
				ErrorUtils.setThrowable(ServletActionContext.getRequest(), ServletActionContext.getResponse(), e);// 把异常添加到request中
				ErrorUtils.setHandlerURL(ServletActionContext.getRequest(), ServletActionContext.getResponse());// 把当前页面信息添加到request中
				throw new ActionException(e);
			} else {
				throw (Exception) e;
			}
		}
		return result;
	}

	/**
	 * 是否SQL异常
	 * 
	 * @param e
	 * @return
	 */
	private boolean isSQLException(Throwable e) {
		boolean result = false;
		if (e instanceof SQLException) {
			result = true;
		} else if (e.getCause() != null) {
			result = isSQLException(e.getCause());
		}
		return result;
	}

}
